const Proxy = require('../../proxy')
const webDataUtil = require('../../util/webDataUtil')
const executeRecordService = require('../executeRecord')
const reqlib = require('app-root-path').require
const btbAs = reqlib('/app/common/btb')
const quantityUtilHY = reqlib('/app/common/btb/quantityUtilHY')

const BtbIndex = Proxy.BtbIndex
const Dictionary = Proxy.Dictionary

const exBuyHY = reqlib('/app/common/btb/exBuyHY')
const exSellHY = reqlib('/app/common/btb/exSellHY')

// 获取合约账户财务信息
module.exports = async function (params) {
  let btbLeverageRes = await Dictionary.findOne({ key: 'btbLeverage' })
  let btbLeverage = parseInt((btbLeverageRes && btbLeverageRes.value) || 1) || 1
  const query = {
    status: 1,
    hy_status: 1
  }
  if (params && params.code) {
    query.code = params.code
  }
  // 找出币
  let btbRes = await BtbIndex.find(query, {
    sort: '-proportion'
  })
  // 总占比
  const btbIndexConfig = {
    proportionAll: 0,
    balance: {},
    btbList: []
  }
  // 查K线
  for (let i = 0; i < btbRes.length; i++) {
    const btbItem = btbRes[i]
    if (btbItem.proportion) {
      btbIndexConfig.proportionAll += btbItem.proportion
      btbIndexConfig.btbList.push({
        name: btbItem.name,
        code: btbItem.code,
        hourEma510: btbItem.hourEma510 || 0,
        hourEmaInfo: btbItem.hourEmaInfo ? btbItem.hourEmaInfo : {},
        dayEmaInfo: btbItem.dayEmaInfo ? btbItem.dayEmaInfo : {},
        strategy: btbItem.strategy,
        // 取合约的信息
        min_qty: btbItem.f_min_qty,
        max_qty: btbItem.f_max_qty,
        step_size: btbItem.f_step_size,
        tick_size: btbItem.f_tick_size,
        min_notional: btbItem.f_min_notional,
        proportion: btbItem.proportion
      })
    }
  }
  if (btbIndexConfig.btbList.length === 0) {
    return false
  }
  // 资产
  const balanceRes = await webDataUtil.binance('getFuturesAccount')
  const myBalance = balanceRes.data || {}
  const positionsList = myBalance.positions || []
  btbIndexConfig.btbList.forEach((v, index) => {
    const astItem = btbAs.getAstItem(positionsList, v.code)
    const available = parseFloat(astItem.positionAmt)
    const notional = parseFloat(astItem.notional)
    btbIndexConfig.btbList[index] = {
      ...v,
      // 份额，多单是正，空单是负数
      balance: available,
      // 市值，多单是正，空单是负数
      usdt: notional,
      // 保证金，正数
      initialMargin: parseFloat(astItem.initialMargin),
      // 杠杆
      leverage: parseFloat(astItem.leverage)
    }
    btbIndexConfig.balance[v.code] = available
  })
  // 执行买入卖出
  for (let i = 0; i < btbIndexConfig.btbList.length; i++) {
    const btbItem = btbIndexConfig.btbList[i]
    if (btbItem.usdt < 0) {
      // 平空，直接算持仓的数量
      let val = 0 - btbItem.balance
      const quantity = quantityUtilHY.formatValPing(val, btbItem)
      const exRes = await exBuyHY({
        usdtKey: `${btbItem.code}USDT`,
        quantity: quantity,
        btbItem,
        btbLeverage
      })
      if (exRes) {
        await executeRecordService.addExecuteRecord({
          code: btbItem.code,
          type: 'pingKong',
          leverage: btbLeverage,
          quantity: quantity,
          btbItem,
          reason: 'manual'
        })
      }
    } else if (btbItem.usdt > 0) {
      // 平多，直接算持仓的数量
      let val = btbItem.balance - 0
      const quantity = quantityUtilHY.formatValPing(val, btbItem)
      const exRes = await exSellHY({
        usdtKey: `${btbItem.code}USDT`,
        quantity: quantity,
        btbItem,
        btbLeverage
      })
      if (exRes) {
        await executeRecordService.addExecuteRecord({
          code: btbItem.code,
          type: 'pingDuo',
          leverage: btbLeverage,
          quantity: quantity,
          btbItem,
          reason: 'manual'
        })
      }
    }
  }
  return {}
}
